<template>
<div class="bgimg">
  <div class="main">
    <message :top1="top1" :visible3="visible3" :xfmsg="xfmsg" :left ="left1" />
    <div v-show="visible">
      <ul id="menu" class="menu"  v-show="visible" :style="{left:left+'px',top:top+'px'}">
        <li class="menu__item" @click="">查看好友</li>
        <li class="menu__item" @click="doDelete()">好友删除</li>
      </ul>
    </div>
      <div class="friend">
        <el-menu
         :default-openeds="openeds"
          @open="handleOpen"
          @close="handleClose"
          background-color="white"
          text-color="black">
          <el-submenu index="1">
          <template slot="title">
            <i class="el-icon-user-solid"></i>
            <span>好友列表</span>
          </template>
          <el-menu-item-group v-for="(friend,index) in friends" :key="index">
            <el-menu-item  ref="where" @click="getid(friend)" @contextmenu.prevent.native ="openMenu($event,friend.id)" 
            style="padding-left:20px;min-width:100%;color:black" 
            >
              <img :src="friend.pic" style="width:40px;margin-right:10px" @mouseover="doMsg($event,friend.id)"
            @mouseout="doXiaoshi()" alt="">
              {{friend.userName}}
            </el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>
      </div>
      <div style="height:6%;background-color: white;">
        <back style="position:absolute;left:22%;z-index:3000" @click.native="back()" />
        <p style="text-align :center;background-color: white;width: 80%;left: 20%;position: relative;">{{friendName}}</p></div>
      <div id="context" ref="context" @scroll="scollEvent($event)">
        <p v-show="history" style="font-size:10px;margin-top:0;position:relative;left:45%" @click="hisMsg()">点击获取历史消息</p>
        <div class="loader" v-show="loader" style="position:relative;left:48%"></div>
        <div v-for="(item,index) in list" :key="index"  style="">
          <p class="time">{{getTime(item.sendTime)}}</p>
            <div v-if="item.fromUserId == fromUserId" class="item right">
             <img :src="imgI" style="width:35px;height:35px;margin:5px;border-radius:50%" @mouseover="doMsg($event,fromUserId)"
            @mouseout="doXiaoshi()" />
              <span class="message" >
                {{item.message}}
              </span>
            </div>
            <div v-else class="item left"> 
              <img :src="imgY" style="width:35px;height:35px;margin:5px;border-radius:50%" @mouseover="doMsg($event,item.fromUserId)"
            @mouseout="doXiaoshi()" />
              <span class="message-self" >
                {{item.message}}
              </span>
            </div>
        </div>
      </div>
      <el-input class="input" type="textarea" :rows="7" resize="none" ref="sendMsg" v-model="sendmessage" > 
      </el-input>
      <el-button size="mini" type="primary" style="top:95%;position:absolute;right:0.1%" @click="send()">发送</el-button>
       <!-- <el-button size="mini" type="primary" style="top:95%;position:absolute;right:6%" @click="back()">返回</el-button> -->
  <router-view />
  </div>
</div>
</template>

<script>
import message from '../components/message.vue'
import back from '../components/back.vue'
export default {
  components:{
    message,back
  },
  data () {
    return {
      openeds: ['1'],
      uniqueOpened: false,
      ws:null,
      msg: '',
      //当前系统时间
      nowYear: '',
      nowMouth: '',
      nowDate: '',
      nowWeek: '',
      friends:[],
      friendName:'',
      time:'',
      //发送的消息
      sendmessage:'',
      //保存消息记录到数组
      list:[],
      fromUserId:'',
      fromName:'',
      toUserId:'',
      //当前用户名称
      username:'',
      last:'',
      imgI:'',//自己的头像地址
      imgY:'',//好友的头像地址
      firstTime:'0',
      visible: false,
			top: 0,
      left: 0,
      deleteId:'',
      signature:'',
      visible3: false,
      top1:'',
      xfmsg:[],
      left1:'',
      history:false,
      loader:false,
      timer:'',
    }
  },
  created() {
  },
  mounted(){
    this.toUserId = localStorage.getItem('toUserId')
    this.username = localStorage.getItem('username');
    this.fromUserId = localStorage.getItem('fromUserId');
    this.friendName = localStorage.getItem('friendName')
    this.getImage(this.fromUserId)
    this.getImage(this.toUserId)
    this.getFriends(this.fromUserId);
    this.initWebSocket();
    this.getMessage();
  },
  destroyed() {
      // 离开页面时关闭websocket连接
      this.ws.onclose(undefined);
    },
    
  methods: {
     //右键点击删除触发事件
    openMenu(e,id) {
      const menuMinWidth = 105
      const offsetLeft = e.target.getBoundingClientRect().left // container margin left
      const offsetWidth = e.target.offsetWidth // container width
      const maxLeft = offsetWidth - menuMinWidth // left boundary
      const left = e.clientX - offsetLeft // 15: margin right

      if (left > maxLeft) { 
        this.left = maxLeft
      } else {
        this.left = left
      }
      this.top = e.clientY - 60 // fix 位置bug
      this.visible = true
      this.deleteId = id;
    },
    closeMenu() {
      this.visible = false
    },
    scollEvent(e){
      if(e.srcElement.scrollTop ==0){
        this.history = true
      }else{
        this.history = false
        this.loader = false
      }
    },
    getid(friend){
      this.toUserId = friend.id;
      this.friendName = friend.userName;
      localStorage.setItem('toUserId',this.toUserId)
      localStorage.setItem('friendName',this.friendName)
      this.getImage(this.toUserId)
      console.log(this.imgI)
      this.getMessage();
    },
    getImage(id){
      let _this =this
      if(id == this.fromUserId){
      this.$axios.get('/api/website/user/info/'+id).then((resp) =>{
        _this.imgI = resp.user.pic
        
      })}else{
          this.$axios.get('/api/website/user/info/'+id).then((resp) =>{
        _this.imgY = resp.user.pic
        
      })
      }
    },
    getTime(time){
      var newTime = Date.parse(time)  //获取参数time的时间戳
      var lasttime = localStorage.getItem('last')
      localStorage.setItem('last',newTime)  //根据消息的时间错存储消息的时间
      if(((newTime - lasttime)>1000 *10)){
      var date = new Date(time);
      const year = date.getFullYear()
      const mounth = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var result =year+ "-"+mounth+"-"+ day+" "+ time.substring(11,19)
      return result;
    }else{
      return null
    }
    },
    getMessage(){
      var a= JSON.parse(localStorage.getItem(this.toUserId))
      if(a != null){
          this.list = a
      } else{
        this.list = []
        this.history = true
      }
      this.scrollBottm();
    },
    getFriends(f){
      this.$axios.get('/api/socket/relationship/info/'+f).then((resp) =>{
        this.friends = resp.relationship.friends
      })
    },
    hisMsg(){
      const params ={
        page:1,
        limit:10,
        fromUserId : this.fromUserId,
        toUserId : this.toUserId
      }
      this.loader = true
      this.history = false
      this.timer = 
      setTimeout(() =>{
        this.loader = false
        this.$axios.get('api/socket/message/list',{params,headers:{isloading :false}}).then((resp) =>{
        if(resp.page.list.length !=0){
        this.list =resp.page.list  
        }else{
          this.$message.error('暂无历史消息')
        }   
      })
      },1000)
      
    },
    doMsg(e,id){
      let top = e.target.getBoundingClientRect().top
      this.left1 = e.target.getBoundingClientRect().left - 250
      this.visible3 = true 
      this.top1 = top-200
      this.$axios.get('api/website/user/info/'+id,{
        headers:{isloading:false}
      }).then((resp) =>{
        this.xfmsg = resp.user
        if(resp.user.sex == true){
          this.xfmsg.sex = '男'
        }else{
          this.xfmsg.sex = '女'
        }
      
      })
    },
    doXiaoshi(){
      // console.log(this.visible3)
      this.visible3 = false
      // console.log(this.visible3)
      
    },
    handleOpen(key, keyPath) {
        console.log(key, keyPath);
      },
      handleClose(key, keyPath) {
        console.log(key, keyPath);
      },
        //进入页面创建websocket连接
    initWebSocket() {
      let _this = this
      //判断页面有没有存在websocket连接
      if(window.WebSocket){
        let ws = new WebSocket("wss://chat.lomtom.top/wss/"+this.fromUserId)
        _this.ws = ws;
        ws.onopen = function(e){
          console.log("服务器连接成功")
        }
        ws.onclose = function(e){
          console.log("服务器连接关闭")
        }
        ws.onerror = function(){
          console.log("服务器连接出错")
        }
        ws.onmessage = function(e) { 
          //接收服务器返回的数据
          let a =JSON.parse(e.data)
          console.log(a)
          // console.log(e.data)
          if(a.isMessage == false){
            _this.$message.error(a.message)
          }
          if(((a.fromUserId == _this.fromUserId && a.toUserId == _this.toUserId)) || ((a.fromUserId ==  _this.toUserId&& a.toUserId == _this.fromUserId))){
          _this.list.push(JSON.parse(e.data))
          localStorage.setItem(_this.toUserId,JSON.stringify(_this.list))
          _this.scrollBottm();
          }else{
            return
          }
          }
      }
    },
    send(){
      let _this = this
      // 发送完信息之后失去焦点
      this.$refs["sendMsg"].focus()
      // 判断如果输入位空，则不向服务器发送数据
      if(!this.sendmessage){
        return
      }
       let params = {
         fromUserId: this.fromUserId,
         toUserId: this.toUserId,
         message: this.sendmessage
       }
      //调用WebSocket send()发送信息的方法
      this.ws.send(JSON.stringify(params))
      this.sendmessage = ""
    },
    back(){
      this.$router.push('/home')
    },
    //保持滚动条一直显示在底部
    scrollBottm() {
        this.$nextTick(()=>{
         let context = document.getElementById('context')
         context.scrollTop = context.scrollHeight;
        })
       }
  }
}
</script>

<style scoped>
.main{
    height: 577px;
    width: 1075px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    /* border:1px solid ; */
    background-color: white;
    
}
.friend{
    height: 100%;
    width: 20%;
    position: absolute;
    left: 0;
    /* border: 1px solid; */
    float: left;
    background-color: white;
}
#context{
    height: 68%;
    width: 80%;
    position: relative;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    left: 20%;
    overflow-y: scroll;
    overflow-x: hidden;
    background-color: #f3efef;
    /* border: 1px solid; */
}
#context::-webkit-scrollbar{

  /*滚动条整体样式*/
  width : 10px;  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
  }
#context::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius   : 10px;
  background-color: rgb(135, 178, 235);
  background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
  );
  }
#context::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow   : inset 0 0 5px rgba(247, 244, 244, 0.74);
  background   : #ededed;
  border-radius: 10px;
  }
.input{ 
    width: 80%;
    position: relative;
    left: 20%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    /* border: 1px solid; */
}
.item {
	display: flex;
	margin-bottom: 10px;
}

.left {
	flex-direction: row;
}

.right {
	flex-direction: row-reverse;
}


.message-self {
	border-radius: 10px;
	display: flex;
	background: white;
	max-height: 35px;
  margin-top:5px ;
	align-items: center;
	color: #222121;
  padding:0px 10px;
}

.message {
	border-radius: 10px;
	display: flex;
	background: rgb(207, 226, 236);
	max-height: 35px;
  margin-top:5px ;
  padding-bottom: 0;
	padding: 9px 10px;
	align-items: center;
	color: #222121;
}
.message:hover{
  background: #ededed;
}
.time{
  text-align: center;
  font-size: 8px;
}
 .loader{
            border:3px solid #f3f3f3;
            border-color:#00ffff #00ccff #0099ff #0066ff;
            border-radius: 50%;
            width:10px;
            height:10px;
            animation:load 2s linear infinite;
        }
        @keyframes load{
            0%{
                transform:rotate(0deg);
            }
            100%{
                transform:rotate(360deg);
            }
        }
        .bgimg {
		position: absolute;
		background: url(../assets/bg.png) no-repeat center;
		background-size: cover;
		height: 100%;
		width: 100%;
	}
   .menu__item {
    list-style-type: none;
    line-height: 20px;
    left:auto;
    width: 100px;
    margin-top: 10px;
    margin-bottom: 10px;
    text-align: center;
    /* font-size: 12px; */
    font-family:Tahoma;
  }
    .menu {
    padding:0;
    z-index: 3000;
    width: 100px;
    position: absolute;
    border-radius: 10px;
    border: 1px solid #999999;
    background-color: #f4f4f4;
  }
   .menu__item:hover {
    background-color: #1790ff;
    color: white;
  }
</style>
<style>
.el-textarea__inner{
  border: none;
  line-height: 1.3;
  min-height: 137px;
}

</style>
